package ace.cmp.security.oauth2.resource.server.core.web.access;

import ace.cmp.core.enums.SystemCodeEnum;
import ace.cmp.core.model.R;
import ace.cmp.json.api.JsonService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 * @author caspar
 * @date 2023/3/14 17:25
 */
public class ResourceServerAccessDeniedHandler implements AccessDeniedHandler {
  private final JsonService jsonService;

  public ResourceServerAccessDeniedHandler(JsonService jsonService) {
    this.jsonService = jsonService;
  }

  @Override
  public void handle(
      HttpServletRequest request,
      HttpServletResponse response,
      AccessDeniedException accessDeniedException)
      throws IOException {
    R<String> result =
        R.<String>builder()
            .message(SystemCodeEnum.ERROR_HTTP_403_EXCEPTION.getDesc())
            .data(accessDeniedException != null ? accessDeniedException.getMessage() : "")
            .code(HttpStatus.FORBIDDEN.value())
            .build();

    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(HttpStatus.FORBIDDEN.value());
    PrintWriter printWriter = response.getWriter();
    printWriter.append(jsonService.toJson(result));
  }
}
